package tcdx.uap.controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tcdx.uap.common.utils.Lutils;
import tcdx.uap.mapper.BaseDBMapper;
import tcdx.uap.service.BaseDBService;
import tcdx.uap.service.CommonDBService;
import tcdx.uap.service.ExcelService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/uap/excel")
public class ExcelController {
    private static final String ROOT_PATH="C:"+File.separator+"files";

    @Autowired
    private BaseDBService baseDBService;
    @Autowired
    private ExcelService excelService;
    @Autowired
    private CommonDBService commonDBService;

    @PostMapping( "/exportMoBan")
    @ResponseBody
    public void exportMoBan(@RequestBody Map map, HttpServletResponse response) throws Exception {
        Object table_id = map.get("table_id");

//        commonDBService.selectEq("tcdx_task_tableview_columns",
//                Lutils.genMap("tableview_id", tableview_id),null);
        List<Map> columns_list = baseDBService.selectEq("tcdx_datatable_columns",
                Lutils.genMap("table_id",table_id));


        List<List<String>> headList = new ArrayList();
        List<List<String>> dataList = new ArrayList();

        for (int i = 0; i < columns_list.size(); i++) {
            Map column = columns_list.get(i);
            String name = column.get("label_title").toString();
            headList.add(new ArrayList() {{
                add(name);
            }});
        }

        List<String> items = new ArrayList<>();
        for (int i = 0; i < columns_list.size(); i++) {
            Map oneData = (Map) columns_list.get(i);
            items.add(oneData.get("field").toString());
        }

        dataList.add(items);

        List<String> items2 = new ArrayList<>();
        for (int i = 0; i < columns_list.size(); i++) {
            Map oneData = (Map) columns_list.get(i);
            items2.add(oneData.get("column_type").toString());
        }

        dataList.add(items2);


        //List<List<String>> list = dataList();
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景设置为蓝色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, new WriteCellStyle());

        WriteFont headWriteFont = new WriteFont();
        //headWriteFont.setFontHeightInPoints((short)16);
        headWriteCellStyle.setWriteFont(headWriteFont);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("模板文件", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream())
                //加载样式
                .registerWriteHandler(horizontalCellStyleStrategy)
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                // 这里放入动态头
                .head(headList).sheet("demo")
                // 当然这里数据也可以用 List<List<String>> 去传入
                .doWrite(dataList);
    }


    @PostMapping("/upload")
    @ResponseBody
    public Map upload(MultipartFile file) throws IOException {
        String originFilename= file.getOriginalFilename();
        String mainName= FileUtil.mainName(originFilename);
        String extName=FileUtil.extName(originFilename);
        if(!FileUtil.exist(ROOT_PATH)){
            FileUtil.mkdir(ROOT_PATH);
        }
        if(FileUtil.exist(ROOT_PATH+File.separator+originFilename)){
            originFilename=System.currentTimeMillis()+"_"+mainName+"."+extName;
        }
        File saveFile=new File(ROOT_PATH+File.separator+originFilename);
        file.transferTo(saveFile);
        String url=ROOT_PATH+originFilename;
        Map<String, Object> map =
                Lutils.genMap("display_name",
                originFilename, "url", url);
        return map;
    }

    @GetMapping("/download/{filename}")
    public void download(@PathVariable String filename, HttpServletResponse response) throws IOException {
//        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")); // 附件下载
        response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(filename, "UTF-8")); // 预览
        String filePath=ROOT_PATH+ File.separator+filename;
        if(!FileUtil.exist(filePath)){
            return;
        }
        byte[] bytes=FileUtil.readBytes(filePath);
        ServletOutputStream outputStream=response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }


    //导入功能
    @PostMapping(value = "/importExcel", produces = {"text/html;charset=UTF-8;", "application/json;"})
    @ResponseBody
    public String importExcel(MultipartFile file, int menu_id, int table_id) throws IOException {
        try {
            excelService.importExcel(file,menu_id,table_id);
            return "流程任务创建成功";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

}
